<!-- 平台管理-用户管理 -->
<template>
  <div class="platform-user-page art-full-height">
    <!-- 搜索栏 -->
    <UserSearch v-model="searchForm" @search="handleSearch" @reset="resetSearchParams"></UserSearch>

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
        <template #left>
          <ElSpace wrap>
            <ElButton @click="showDialog('add')" v-ripple>新增</ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
      </ArtTable>

      <!-- 用户弹窗 -->
      <UserDialog
        v-model:visible="dialogVisible"
        :type="dialogType"
        :user-data="currentUserData"
        @submit="handleDialogSubmit"
      />

      <!-- 重置密码弹窗 -->
      <ResetPasswordDialog
        v-model:visible="resetPasswordVisible"
        :user-id="currentUserId"
        @submit="handleResetPasswordSubmit"
      />
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import ArtButtonMore from '@/components/core/forms/art-button-more/index.vue'
  import { ButtonMoreItem } from '@/components/core/forms/art-button-more/index.vue'
  import { ElMessageBox, ElMessage, ElTag } from 'element-plus'
  import { Edit, Delete, Key } from '@element-plus/icons-vue'
  import { useTable } from '@/composables/useTable'
  import UserSearch from './modules/user-search.vue'
  import UserDialog from './modules/user-dialog.vue'
  import ResetPasswordDialog from './modules/reset-password-dialog.vue'

  defineOptions({ name: 'PlatformUser' })

  interface PlatformUser {
    id: string
    name: string
    openid: string
    registerSource: string
    phone: string
    password: string
    gender: number
    avatar: string
    registerTime: string
    lastLoginTime: string
  }

  // 弹窗相关
  const dialogType = ref<Form.DialogType>('add')
  const dialogVisible = ref(false)
  const currentUserData = ref<Partial<PlatformUser>>({})

  // 重置密码弹窗
  const resetPasswordVisible = ref(false)
  const currentUserId = ref('')

  // 选中行
  const selectedRows = ref<PlatformUser[]>([])

  // 搜索表单
  const searchForm = ref({
    name: '',
    openid: '',
    registerSource: '',
    gender: '',
    phone: ''
  })

  // 性别配置
  const GENDER_CONFIG = {
    0: { type: 'info' as const, text: '未知' },
    1: { type: 'primary' as const, text: '男' },
    2: { type: 'danger' as const, text: '女' }
  } as const

  // 注册来源配置
  const REGISTER_SOURCE_CONFIG = {
    app: { type: 'success' as const, text: 'APP' },
    miniprogram: { type: 'warning' as const, text: '小程序' }
  } as const

  /**
   * 获取性别配置
   */
  const getGenderConfig = (gender: number) => {
    return (
      GENDER_CONFIG[gender as keyof typeof GENDER_CONFIG] || {
        type: 'info' as const,
        text: '未知'
      }
    )
  }

  /**
   * 获取注册来源配置
   */
  const getRegisterSourceConfig = (source: string) => {
    return (
      REGISTER_SOURCE_CONFIG[source as keyof typeof REGISTER_SOURCE_CONFIG] || {
        type: 'info' as const,
        text: source
      }
    )
  }

  // 模拟数据
  const mockUsers: PlatformUser[] = [
    {
      id: '1',
      name: '张三',
      openid: 'ox1234567890abcdef',
      registerSource: 'app',
      phone: '13800138000',
      password: '******',
      gender: 1,
      avatar: 'https://via.placeholder.com/100',
      registerTime: '2024-01-15 10:30:00',
      lastLoginTime: '2024-10-15 09:20:00'
    },
    {
      id: '2',
      name: '李四',
      openid: 'ox0987654321fedcba',
      registerSource: 'miniprogram',
      phone: '13900139000',
      password: '******',
      gender: 2,
      avatar: 'https://via.placeholder.com/100',
      registerTime: '2024-02-20 14:20:00',
      lastLoginTime: '2024-10-14 16:45:00'
    },
    {
      id: '3',
      name: '王五',
      openid: 'ox1122334455667788',
      registerSource: 'app',
      phone: '13700137000',
      password: '******',
      gender: 1,
      avatar: 'https://via.placeholder.com/100',
      registerTime: '2024-03-10 08:15:00',
      lastLoginTime: '2024-10-15 11:30:00'
    }
  ]

  // 模拟API请求
  const fetchUserList = (params: any) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          code: 200,
          data: {
            records: mockUsers,
            total: mockUsers.length
          }
        })
      }, 300)
    })
  }

  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    // 核心配置
    core: {
      apiFn: fetchUserList,
      apiParams: {
        current: 1,
        size: 20,
        ...searchForm.value
      },
      excludeParams: [],
      columnsFactory: () => [
        { type: 'selection' },
        { prop: 'id', label: 'ID', minWidth: 80 },
        { prop: 'name', label: '名称', minWidth: 120 },
        { prop: 'openid', label: 'OpenID', minWidth: 180 },
        {
          prop: 'registerSource',
          label: '注册来源',
          minWidth: 100,
          formatter: (row) => {
            const config = getRegisterSourceConfig(row.registerSource)
            return h(ElTag, { type: config.type }, () => config.text)
          }
        },
        { prop: 'phone', label: '手机号', minWidth: 120 },
        { prop: 'password', label: '密码', minWidth: 100, formatter: () => '******' },
        {
          prop: 'gender',
          label: '性别',
          minWidth: 80,
          formatter: (row) => {
            const config = getGenderConfig(row.gender)
            return h(ElTag, { type: config.type }, () => config.text)
          }
        },
        {
          prop: 'avatar',
          label: '头像',
          minWidth: 80,
          formatter: (row) =>
            h('img', {
              src: row.avatar,
              style: 'width: 40px; height: 40px; border-radius: 6px;'
            })
        },
        {
          prop: 'registerTime',
          label: '注册时间',
          minWidth: 160,
          sortable: true
        },
        {
          prop: 'lastLoginTime',
          label: '最后登录时间',
          minWidth: 160,
          sortable: true
        },
        {
          prop: 'operation',
          label: '操作',
          minWidth: 180,
          fixed: 'right',
          formatter: (row) =>
            h('div', { style: 'display: flex; align-items: center; gap: 8px;' }, [
              h(ArtButtonTable, {
                type: 'edit',
                onClick: () => showDialog('edit', row)
              }),
              h(ArtButtonTable, {
                type: 'delete',
                onClick: () => deleteUser(row)
              }),
              h(ArtButtonMore, {
                list: [
                  {
                    key: 'resetPassword',
                    label: '重置密码',
                    icon: Key
                  }
                ],
                onClick: (item: ButtonMoreItem) => {
                  if (item.key === 'resetPassword') {
                    showResetPasswordDialog(row)
                  }
                }
              })
            ])
        }
      ]
    },
    // 数据处理
    transform: {
      dataTransformer: (records: any) => {
        if (!Array.isArray(records)) {
          console.warn('数据转换器: 期望数组类型，实际收到:', typeof records)
          return []
        }
        return records
      }
    }
  })

  /**
   * 搜索处理
   */
  const handleSearch = (params: Record<string, any>) => {
    Object.assign(searchParams, params)
    getData()
  }

  /**
   * 显示用户弹窗
   */
  const showDialog = (type: Form.DialogType, row?: PlatformUser): void => {
    console.log('打开弹窗:', { type, row })
    dialogType.value = type
    currentUserData.value = row || {}
    nextTick(() => {
      dialogVisible.value = true
    })
  }

  /**
   * 显示重置密码弹窗
   */
  const showResetPasswordDialog = (row: PlatformUser): void => {
    console.log('打开重置密码弹窗:', row)
    currentUserId.value = row.id
    nextTick(() => {
      resetPasswordVisible.value = true
    })
  }

  /**
   * 删除用户
   */
  const deleteUser = (row: PlatformUser): void => {
    console.log('删除用户:', row)
    ElMessageBox.confirm(`确定要删除用户"${row.name}"吗？`, '删除用户', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(() => {
      ElMessage.success('删除成功')
      refreshData()
    })
  }

  /**
   * 处理弹窗提交事件
   */
  const handleDialogSubmit = async () => {
    try {
      dialogVisible.value = false
      currentUserData.value = {}
      refreshData()
    } catch (error) {
      console.error('提交失败:', error)
    }
  }

  /**
   * 处理重置密码提交事件
   */
  const handleResetPasswordSubmit = async () => {
    try {
      resetPasswordVisible.value = false
      currentUserId.value = ''
    } catch (error) {
      console.error('重置密码失败:', error)
    }
  }

  /**
   * 处理表格行选择变化
   */
  const handleSelectionChange = (selection: PlatformUser[]): void => {
    selectedRows.value = selection
    console.log('选中行数据:', selectedRows.value)
  }
</script>

<style lang="scss" scoped>
  .platform-user-page {
    :deep(.avatar) {
      width: 40px;
      height: 40px;
      border-radius: 6px;
    }
  }
</style>

